package com.example.onlinemusic.Controller;

import com.example.onlinemusic.Mapper.UserMapper;
import com.example.onlinemusic.constants.Constant;
import com.example.onlinemusic.model.Result;
import com.example.onlinemusic.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private UserMapper userMapper;
    //登陆
    @RequestMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        log.info("login,username:{},password:{}", username, password);

        User user = userMapper.selectByUsername(username);

        if (user != null) {
            boolean flag = bCryptPasswordEncoder.matches(password, user.getPassword());
            user.setPassword("");

            if (flag) {
                System.out.println(flag);
                request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY, user);
                User user1 = (User) request.getSession().getAttribute(Constant.USERINFO_SESSION_KEY);
                System.out.println(user1.toString());
                return Result.success("登陆成功",user);
            } else {
                return Result.fail("用户账号密码错误");
            }

        } else {
            return Result.fail("用户不存在");
        }
    }

}
